package com.bodacn.packapp;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.listener.ComboLineColumnChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.ComboLineColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ComboLineColumnChartView;

public class ArrangeActivity extends AppCompatActivity implements View.OnClickListener, ComboLineColumnChartOnValueSelectListener {
    //全局提示;
    Toast curToast;
    TextView text_Arrange_ProcEmpCount,text_Arrange_ProcPlanCount,text_Arrange_ProcUnPlanCount,text_Arrange_ProcBudgetOut,text_Arrange_ProcBalanceRatio;
    Button btn_arrange_return;
    ListView arrangeEmpList,arrangeProcList;
    int numberOfPoints=0;
    private ComboLineColumnChartView arrangeProcColumnChart;
    private ComboLineColumnChartData arrangeProcColumnData;
    private JSONArray empList,procList,chartList;
    String curDepartNo,curOrderNo,curStyleNo,curStyleID;
    SQLiteDatabase mainDB;
    public static final String DB_Name ="bdmes.db";
    private int curWorkTT=0;
    private boolean hasAxes = true;
    private boolean hasPoints = true;
    private boolean hasLines = true;
    private boolean isCubic = false;
    private boolean hasLabels = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_arrange);
        //初始提醒;
        curToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        //初始化界面;
        initView();
        //取参数;
        Bundle paramBundle = this.getIntent().getExtras();
        curDepartNo=paramBundle.getString("DepartNo");
        curOrderNo=paramBundle.getString("OrderNo");
        curStyleNo=paramBundle.getString("StyleNo");
        curStyleID=paramBundle.getString("StyleID");
        curWorkTT=paramBundle.getInt("TT");
        //打开或创建数据库文件;
        mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        //显示工序;
        showProcList(curDepartNo,curOrderNo,curStyleNo,curStyleID);
        showEmpList(curDepartNo,curOrderNo,curStyleNo,curStyleID);
        showBalanceChart();
        //取已排工序数和未排工序数;
        Cursor cur = mainDB.rawQuery("SELECT WorkLineNo FROM ProcList WHERE DepartNo=? and  OrderNo=? and StyleNo=? and StyleID=? and length(WorkArrEmps)>0 ORDER BY ID",new String[]{curDepartNo,curOrderNo,curStyleNo,curStyleID});
        text_Arrange_ProcPlanCount.setText(String.valueOf(cur.getCount()));
        cur = mainDB.rawQuery("SELECT WorkLineNo FROM ProcList WHERE DepartNo=? and  OrderNo=? and StyleNo=? and StyleID=? and length(WorkArrEmps)=0 ORDER BY ID",new String[]{curDepartNo,curOrderNo,curStyleNo,curStyleID});
        text_Arrange_ProcUnPlanCount.setText(String.valueOf(cur.getCount()));
        cur.close();
    }

    //初始化;
    private void initView()
    {
        text_Arrange_ProcEmpCount=(TextView)findViewById(R.id.text_Arrange_ProcEmpCount);
        text_Arrange_ProcPlanCount=(TextView)findViewById(R.id.text_Arrange_ProcPlanCount);
        text_Arrange_ProcUnPlanCount=(TextView)findViewById(R.id.text_Arrange_ProcUnPlanCount);
        text_Arrange_ProcBudgetOut=(TextView)findViewById(R.id.text_Arrange_ProcBudgetOut);
        text_Arrange_ProcBalanceRatio=(TextView)findViewById(R.id.text_Arrange_ProcBalanceRatio);
        //按钮事件;
        btn_arrange_return=(Button)findViewById(R.id.btn_arrange_return);
        btn_arrange_return.setOnClickListener(this);
        //图表;
        arrangeEmpList=(ListView)findViewById(R.id.arrangeEmpList);
        arrangeProcList=(ListView)findViewById(R.id.arrangeProcList);
        arrangeProcColumnChart=(ComboLineColumnChartView)findViewById(R.id.arrangeProcColumnChart);
        arrangeProcColumnChart.setOnValueTouchListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_arrange_return:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onColumnValueSelected(int columnIndex, int subcolumnIndex, SubcolumnValue value) {
        Log.d("onColumnValueSelected","Select----------------------"+value);
        try {
            curToast.setText(procList.getJSONObject(columnIndex).getString("WorkName"));
            curToast.setGravity(Gravity.CENTER, 0, 0);
            curToast.show();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPointValueSelected(int lineIndex, int pointIndex, PointValue value) {

    }

    @Override
    public void onValueDeselected() {

    }

    //显示工序数据;
    private void showEmpList(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID){
        //初始化工序列表;
        try {
            empList=new JSONArray("[]");
            //更新当前款己安排SAM值;
            mainDB.execSQL("update EmpList set EmpCT=0 where DepartNo=?",new String[]{paramDepartNo});
            mainDB.execSQL("Delete from EmpTotalCT");
            mainDB.execSQL("INSERT OR REPLACE INTO EmpTotalCT(DepartNo,EmpNo,OrderNo,StyleNo,EmpCT) Select DepartNo,EmpNo," +
                    "OrderNo,StyleNo,sum(SlowTime) EmpCT from EmpProcList where DepartNo=? and OrderNO=? and StyleNo=? and StyleID=? Group by DepartNo,EmpNo,OrderNo,StyleNo", new String[]{paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
            mainDB.execSQL("update EmpList Set EmpCT=(select EmpCT from EmpTotalCT where EmpList.EmpNo=EmpTotalCT.EmpNo)");
           //显示生产单相关信息;
            Cursor curma = mainDB.rawQuery("SELECT * FROM EmpList WHERE DepartNo=? and EmpCT>0 ORDER BY ID",new String[]{paramDepartNo});
            while (curma.moveToNext())
            {
                String WorkName="";
                String paramEmpNo=curma.getString(curma.getColumnIndex("EmpNo"));
                int WorkCount=0;
                //将数据加载到empList中;
                Cursor cur = mainDB.rawQuery("SELECT * FROM EmpProcList WHERE DepartNo=? and OrderNo=? and StyleNo=? and StyleID=? and EmpNo=? ORDER BY ID",new String[]{paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID,paramEmpNo});
                while (cur.moveToNext()) {
                    Log.d("msg","cur.moveToNext()");
                    WorkCount++;
                    if (WorkName.length()>0) WorkName=WorkName+"\r\n"+cur.getString(cur.getColumnIndex("WorkLineNo"))+"."+cur.getString(cur.getColumnIndex("WorkName"));
                    else WorkName=cur.getString(cur.getColumnIndex("WorkLineNo"))+"."+cur.getString(cur.getColumnIndex("WorkName"));
                }
                cur.close();
                //保存到员工列表;
                Log.d("showEmpList","WorkName:"+WorkName);
                JSONObject empJSON = new JSONObject();
                empJSON.put("EmpNo",curma.getString(curma.getColumnIndex("EmpNo")));
                empJSON.put("EmpName",curma.getString(curma.getColumnIndex("EmpName")));
                empJSON.put("WorkName",WorkName);
                empJSON.put("WorkCount", WorkCount);
                empJSON.put("WorkCT", curma.getString(curma.getColumnIndex("EmpCT")));
                empList.put(empJSON);
            }
            curma.close();
        } catch (JSONException e) {
            e.printStackTrace();
            curToast.setText(e.getMessage());
            curToast.show();

        }
        //显示到工序中;
        final ArrangeEmpListAdapter arrangeEmpListAdapter=new ArrangeEmpListAdapter(this);
        arrangeEmpList.setAdapter(arrangeEmpListAdapter);
    }


    //显示工序数据;
    private void showProcList(String paramDepartNo,String paramOrderNo,String paramStyleNo,String paramStyleID)
    {
         //显示生产单相关信息;
        Cursor curma = mainDB.rawQuery("SELECT * FROM ProcMaList WHERE DepartNo=? and OrderNo=? and StyleNo=? and StyleID=? ORDER BY ID",new String[]{paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        if (curma.getCount()>0) {
            curma.moveToFirst();
            text_Arrange_ProcEmpCount.setText(curma.getString(curma.getColumnIndex("EmpCount")));
            text_Arrange_ProcBudgetOut.setText(curma.getString(curma.getColumnIndex("BudgetOut")));
            text_Arrange_ProcBalanceRatio.setText(curma.getString(curma.getColumnIndex("BalanceRatio")));
        }
        curma.close();
        //将数据加载到empList中;
        Cursor cur = mainDB.rawQuery("SELECT * FROM ProcList WHERE DepartNo=? and  OrderNo=? and StyleNo=? and StyleID=? ORDER BY ID",new String[]{paramDepartNo,paramOrderNo,paramStyleNo,paramStyleID});
        try {
            //初始化工序列表;
            procList=new JSONArray("[]");
            while (cur.moveToNext()) {
                JSONObject empJSON = new JSONObject();
                empJSON.put("ArrangeID",cur.getString(cur.getColumnIndex("ArrangeID")));
                empJSON.put("ArrangeDeID",cur.getString(cur.getColumnIndex("ArrangeDeID")));
                empJSON.put("SchemeID",cur.getString(cur.getColumnIndex("SchemeID")));
                empJSON.put("OrderNo", cur.getString(cur.getColumnIndex("OrderNo")));
                empJSON.put("StyleNo", cur.getString(cur.getColumnIndex("StyleNo")));
                empJSON.put("StyleID", cur.getString(cur.getColumnIndex("StyleID")));
                empJSON.put("StyleProID", cur.getString(cur.getColumnIndex("StyleProID")));
                empJSON.put("Part", cur.getString(cur.getColumnIndex("Part")));
                empJSON.put("PartIndex", cur.getString(cur.getColumnIndex("PartIndex")));
                empJSON.put("WorkLineNo", cur.getString(cur.getColumnIndex("WorkLineNo")));
                empJSON.put("WorkNo", cur.getString(cur.getColumnIndex("WorkNo")));
                empJSON.put("WorkName", cur.getString(cur.getColumnIndex("WorkName")));
                empJSON.put("MachineName", cur.getString(cur.getColumnIndex("MachineName")));
                empJSON.put("SlowTime", cur.getString(cur.getColumnIndex("SlowTime")));
                empJSON.put("WorkCT", cur.getString(cur.getColumnIndex("WorkCT")));
                empJSON.put("WorkArrEmps", cur.getString(cur.getColumnIndex("WorkArrEmps")));
                empJSON.put("WorkArrEmpNos", cur.getString(cur.getColumnIndex("WorkArrEmpNos")));
                empJSON.put("SelSign",(boolean)false);
                procList.put(empJSON);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("msg","创建empList----Json出错");
        }
        Log.d("msg","showProcList----记录条数为:"+cur.getCount());
        cur.close();
        //显示到工序中;
        final ArrangeProcListAdapter arrangeProcListAdapter=new ArrangeProcListAdapter(this);
        arrangeProcList.setAdapter(arrangeProcListAdapter);
    }

    public final class ArrangeProcListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ArrangeProcListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return procList.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return procList.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.activity_arrange_prochead, null, false);
            int selectListWidth=parent.getWidth();
            //convertView.setLayoutParams(new ListView.LayoutParams((int)selectListWidth,(int)(40)));
            int ct_max_background = getResources().getColor(R.color.ct_max_background);
            int ct_nor_background = getResources().getColor(R.color.ct_nor_background);
            try {
                if (procList.optJSONObject(position).getInt("WorkCT")>0)
                {
                    if (procList.optJSONObject(position).getInt("WorkCT")>curWorkTT)
                        convertView.setBackgroundResource(R.drawable.item_red_background);
                    else convertView.setBackgroundResource(R.drawable.item_blue_background);
                }else convertView.setBackgroundResource(R.drawable.item_yellow_background);;
                TextView tv = (TextView) convertView.findViewById(R.id.text_arrange_procWorkLineNo);// 显示文字
                tv.setText(procList.optJSONObject(position).get("WorkLineNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_arrange_procWorkNo);// 显示文字
                tv.setText(procList.optJSONObject(position).get("WorkNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_arrange_procWorkName);// 显示文字
                tv.setText(procList.optJSONObject(position).get("WorkName").toString());
                tv.setGravity(Gravity.LEFT);
                tv = (TextView) convertView.findViewById(R.id.text_arrange_procEmpName);// 显示文字
                tv.setText(procList.optJSONObject(position).get("WorkArrEmps").toString());
                tv.setGravity(Gravity.LEFT);
                tv = (TextView) convertView.findViewById(R.id.text_arrange_procWorkCT);// 显示文字
                tv.setText(procList.optJSONObject(position).get("WorkCT").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d("msg","ProcGridAdapter_position:"+position);
            return convertView;
        }
    }

    public final class ArrangeEmpListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ArrangeEmpListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return empList.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return empList.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.activity_arrange_emphead, null, false);
            int selectListWidth=parent.getWidth();
            //convertView.setLayoutParams(new ListView.LayoutParams((int)selectListWidth,(int)(40)));
            int ct_max_background = getResources().getColor(R.color.ct_max_background);
            int ct_nor_background = getResources().getColor(R.color.ct_nor_background);
            try {
                TextView tv = (TextView) convertView.findViewById(R.id.text_arrange_empEmpNo);// 显示文字
                tv.setText(empList.optJSONObject(position).get("EmpNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_arrange_empEmpName);// 显示文字
                tv.setText(empList.optJSONObject(position).get("EmpName").toString());
                tv = (TextView) convertView.findViewById(R.id.text_arrange_empWorkName);// 显示文字
                tv.setText(empList.optJSONObject(position).get("WorkName").toString());
                tv.setGravity(Gravity.LEFT);
                tv = (TextView) convertView.findViewById(R.id.text_arrange_empWorkCount);// 显示文字
                tv.setText(empList.optJSONObject(position).get("WorkCount").toString());
                tv = (TextView) convertView.findViewById(R.id.text_arrange_empWorkCT);// 显示文字
                tv.setText(empList.optJSONObject(position).get("WorkCT").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d("msg","EmpGridAdapter_position:"+position);
            return convertView;
        }
    }

    /**
     *
     */
    //显示图表;
    private void showBalanceChart()
    {
        //根据当前合约找到款的工序分配信息;
        Cursor cur = mainDB.rawQuery("SELECT * FROM ProcList WHERE DepartNo=? and OrderNo=? and StyleNo=? and StyleID=? ORDER BY ID",new String[]{curDepartNo,curOrderNo,curStyleNo,curStyleID});
        numberOfPoints = cur.getCount(); //图上的座标数，即工序数;
        Log.d("msg","showBalanceChart()----------------------------------------------------->1");
        int reindex=0;
        //初始化工序列表;
        List<AxisValue> axisValues = new ArrayList<AxisValue>();
        List<Column> columns = new ArrayList<Column>();
        List<SubcolumnValue> subcolValues;
        List<Line> lines = new ArrayList<Line>();
        List<PointValue> aPointValues=new ArrayList<PointValue>();
        List<PointValue> bPointValues=new ArrayList<PointValue>();
        try {
            chartList=new JSONArray("[]");
            while (cur.moveToNext()) {
                JSONObject procJSON = new JSONObject();
                procJSON.put("WorkIndex", reindex);
                procJSON.put("WorkNo", cur.getString(cur.getColumnIndex("WorkNo")));
                procJSON.put("WorkLineNo", cur.getString(cur.getColumnIndex("WorkLineNo")));
                procJSON.put("WorkName", cur.getString(cur.getColumnIndex("WorkName")));
                procJSON.put("SlowTime", cur.getString(cur.getColumnIndex("SlowTime")));
                procJSON.put("WorkCT", cur.getInt(cur.getColumnIndex("WorkCT")));
                chartList.put(procJSON);
                int slowTime=cur.getInt(cur.getColumnIndex("SlowTime"));
                String colLable=cur.getString(cur.getColumnIndex("WorkLineNo"));
                float WorkCT=cur.getFloat(cur.getColumnIndex("WorkCT"));
                //多个子柱对比时可加多个值;
                subcolValues=new ArrayList<SubcolumnValue>();
                subcolValues.add(new SubcolumnValue(slowTime, ChartUtils.COLORS[0]));
                //添加列并在柱子上方加值显示;不仅仅是在选择时显示;
                columns.add(new Column(subcolValues).setHasLabelsOnlyForSelected(true).setHasLabels(true));
                //多个线条时,可多加值;
                aPointValues.add(new PointValue(reindex, WorkCT));
                //bPointValues.add(new PointValue(reindex, curWorkTT));
                //X轴标签;
                axisValues.add(new AxisValue(reindex).setLabel(colLable));
                reindex++;
            }
            cur.close();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建柱状图数据;
        ColumnChartData columnChartData = new ColumnChartData(columns);
        //A线形图数据;
        Line line = new Line(aPointValues);
        line.setColor(ChartUtils.COLORS[1]);
        line.setCubic(isCubic);
        line.setHasLabels(hasLabels);
        line.setHasLines(hasLines);
        line.setHasPoints(hasPoints);
        lines.add(line);
        //B线形图数据;
        bPointValues.add(new PointValue(0, curWorkTT));
        bPointValues.add(new PointValue(reindex-1, curWorkTT));
        line = new Line(bPointValues);
        line.setColor(ChartUtils.COLORS[2]);
        line.setCubic(isCubic);
        line.setHasLabels(hasLabels);
        line.setHasLines(hasLines);
        line.setHasPoints(hasPoints);
        lines.add(line);
        //创建线形数据;
        LineChartData lineChartData = new LineChartData(lines);
        //创建图形数据;
        arrangeProcColumnData=new ComboLineColumnChartData(columnChartData, lineChartData);
        //国形控制格式;
        if (hasAxes) {
            Axis axisX = new Axis();
            Axis axisY = new Axis().setHasLines(true);
            axisX.setName("工序");
            axisY.setName("时间(秒)");
            axisX.setHasTiltedLabels(true);
            axisX.setHasSeparationLine(true);
            axisX.setValues(axisValues);
            axisY.setTextColor(R.color.black);
            axisX.setTextColor(R.color.black);
            arrangeProcColumnData.setAxisXBottom(axisX);
            arrangeProcColumnData.setAxisYLeft(axisY);
            //测试
            //mainCTColumnData.setAxisXBottom(new Axis(axisValues).setHasLines(true));
            //mainCTColumnData.setAxisYLeft(new Axis().setHasLines(true).setMaxLabelChars(2));

        } else {
            arrangeProcColumnData.setAxisXBottom(null);
            arrangeProcColumnData.setAxisYLeft(null);
        }
        //显示图表;
        arrangeProcColumnChart.setComboLineColumnChartData(arrangeProcColumnData);
        //仅横向允许放大;
        arrangeProcColumnChart.setValueSelectionEnabled(false);
        arrangeProcColumnChart.setZoomEnabled(true);
        arrangeProcColumnChart.setZoomType(ZoomType.HORIZONTAL);
    }
}
